﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Century.Common.Business.BOL.Core;
using Century.Common.Business;
using Telerik.Web.Mvc;
using Century.Models.Core;
using Century.Web.Security.Attributes;
using Century.Web.UI.MVC;
using Century.Business.Repository;

namespace Century.Admin.Controllers
{
    [Authorization(Group = "", Name = "EmailTemplate")]
    public class EmailTemplateController : CenturyAdminBaseController
    {
        EmailTemplateBSO emailTempBSO = PersistData.IsFSA ? BSOInvoker.GetFsaBSO<EmailTemplateBSO>() : BSOInvoker.GetNonFsaBSO<EmailTemplateBSO>();

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetEmailTemplateList(string templateName)
        {
            if (emailTempBSO.GetEmailTemplateList(PersistData.CurrentSite.Id).Count() == 0)
            {
                CopyForCountrySite(PersistData.CurrentSite.Id);
            }
            var model = new GridModel
            {
                Data = string.IsNullOrEmpty(templateName) ?
                emailTempBSO.GetEmailTemplateList(PersistData.CurrentSite.Id)
                .Select(e => new { e.Id, e.CountrySiteId, e.Name, e.Subject, e.Version, e.Body }).OrderBy(c => c.Name)
                :
                emailTempBSO.GetEmailTemplateList(PersistData.CurrentSite.Id).Where(c => c.Name == templateName)
                 .Select(e => new { e.Id, e.CountrySiteId, e.Name, e.Subject, e.Version, e.Body }).OrderBy(c => c.Name)
            };
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        [GridAction]
        public ActionResult EditEmailTemplate(int id)
        {
            EmailTemplate oldEmailTemplate = emailTempBSO.Find(c => c.Id == id, "EmailFileTypes");
            EmailTemplate emailTemplate = new EmailTemplate();
            TryUpdateModel(emailTemplate);
            emailTemplate.Version++;
            emailTemplate.EmailFileTypes = new List<EmailFileType>();
            foreach (var item in oldEmailTemplate.EmailFileTypes)
            {
                emailTemplate.EmailFileTypes.Add(item);
            }
            emailTempBSO.Insert(emailTemplate);
            var model = new GridModel
            {
                Data = emailTempBSO.GetEmailTemplateList(PersistData.CurrentSite.Id)
                .Select(e => new { e.Id, e.CountrySiteId, e.Name, e.Subject, e.Version, e.Body }).OrderBy(c => c.Name)
            };
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        [GridAction]
        public ActionResult InsertEmailTemplate()
        {
            EmailTemplate emailTemplate = new EmailTemplate();
            TryUpdateModel(emailTemplate);
            emailTempBSO.Insert(emailTemplate);
            var model = new GridModel
            {
                Data = emailTempBSO.GetEmailTemplateList(PersistData.CurrentSite.Id)
                .Select(e => new { e.Id, e.CountrySiteId, e.Name, e.Subject, e.Version, e.Body }).OrderBy(c => c.Name)
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult GetTemplateNames(string text)
        {
            List<string> temps = emailTempBSO.GetDistinctedTemplates();
            var query = temps.Select(c => new { TemplateId = c, templateName = c });

            if (!string.IsNullOrEmpty(text))
            {
                query = temps.Where(c => c.StartsWith(text)).Select(c => new { TemplateId = c, templateName = c });
            }
            return new JsonResult
            {
                Data = new SelectList(query.AsEnumerable(), "TemplateId", "TemplateName")
            };

        }

        [GridAction]
        public ActionResult DetailsForEmailTemplate(int templateId)
        {
            var confDetails = emailTempBSO.GetEmailTemplateFiles(templateId).Select(c =>
                new
                {
                    c.Id,
                    c.Name,
                    c.MediaType
                });
            return View(new GridModel(confDetails));
        }

        private void CopyForCountrySite(int id)
        {
            var defaultTemplates = emailTempBSO.GetEmailTemplateListWithFiles(PersistData.IsFSA ? 14 : 15);

            foreach (var item in defaultTemplates)
            {
                EmailTemplate template = new EmailTemplate
                {
                    CountrySiteId = id,
                    Name = item.Name,
                    Subject = item.Subject,
                    Version = 1,
                    Body = item.Body
                };

                if (item.EmailFileTypes != null && item.EmailFileTypes.Count > 0)
                {
                    template.EmailFileTypes = new List<EmailFileType>();
                    foreach (var file in item.EmailFileTypes)
                    {
                        EmailFileType newFile = new EmailFileType { Content = file.Content, MediaType = file.MediaType, Name = file.Name };
                        template.EmailFileTypes.Add(newFile);
                    }
                }

                using (EmailTemplateBSO emBso = (PersistData.IsFSA ? BSOInvoker.GetFsaBSO<EmailTemplateBSO>() : BSOInvoker.GetNonFsaBSO<EmailTemplateBSO>()))
                {
                    emBso.Insert(template);
                }
            }
        }


    }
}
